package com.intretech.umsin.pay.conrtoller;

import com.alipay.api.AlipayApiException;
import com.intretech.umsin.common.utils.DateUtils;
import com.intretech.umsin.pay.component.AlipayTemplate;
import com.intretech.umsin.pay.service.PayMentService;
import com.intretech.umsin.pay.vo.AlipayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @version V1.0
 * @ClassName: AlipayController
 * @Description: 功能描述
 * @author: 李启联
 * @date: 2022-8-12 9:22
 * @Copyright: Copyright (c) 2022
 */
@Controller
@Slf4j
public class AlipayController {

    @Autowired
    private PayMentService payMentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 支付接口
     * @param machineId
     * @return
     * @throws AlipayApiException
     */
    @ResponseBody
    @GetMapping( value = "/goAlipay",produces = "text/html")
    public String goAliPay(@RequestParam("machineId") String machineId) throws AlipayApiException {
        AlipayVo vo = payMentService.getAlipay(machineId);
        return alipayTemplate.pay(vo);
    }

    /**
     * 支付成功后的支付宝异步通知
     */
    @RequestMapping(value="/alipay")
    public String alipay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付成功后的支付宝异步通知");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//       valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);
        boolean signVerified = alipayTemplate.signVerified(params); //调用SDK验证签名

        if(signVerified) {//验证成功
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")){
                log.info("************** 交易成功 *************");
            }

            log.info("************* 支付成功(支付宝异步通知) - 时间: {} *************", DateUtils.getNowDate());
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 交易状态: {}", trade_status);
            log.info("*****************************************************************************");

            return "success";
        }else {
            //验证失败
            log.info("验签失败, 时间: {}", DateUtils.getNowDate());
            return "fail";
        }

    }




}